package top.lixunda.ecommerce.server.good.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.stereotype.Component;

/**
 * @author Xumda
 * @version time:2019/11/26 9:15
 */
@Component("springSessionDefaultRedisSerializer")
@Primary
@Slf4j
public class SpringSessionSerializedConfig extends JdkSerializationRedisSerializer {

    private final ObjectMapper DEFAULT_OBJECT_MAPPER = getObjectMapper();

    private final GenericJackson2JsonRedisSerializer decoder = new GenericJackson2JsonRedisSerializer(DEFAULT_OBJECT_MAPPER);

    private final GenericJackson2JsonRedisSerializer encoder = new GenericJackson2JsonRedisSerializer(DEFAULT_OBJECT_MAPPER);

    public SpringSessionSerializedConfig() {
        log.debug("配置 SpringSessionSerializedConfig");
    }

    /**
     * 获取ObjectMapper
     *
     * @return ObjectMapper
     */
    private ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

    @Override
    public Object deserialize(byte[] bytes) {
        return decoder.deserialize(bytes);
    }

    @Override
    public byte[] serialize(Object object) {
        return encoder.serialize(object);
    }

    /**
     * 取消防CSRF攻击的cookies，但会导致跨域时无法携带cookies导致session不一致问题
     *
     * @return CookieSerializer
     */
    @Bean
    public CookieSerializer httpSessionIdResolver() {
        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
        cookieSerializer.setSameSite(null);
        return cookieSerializer;
    }
}
